﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using coffeeshop.Models;


namespace coffeeshop.Forms
{
    public partial class frmLoginForm : Form
    {
        public frmLoginForm()
        {
            InitializeComponent();

            LoadLastUsername();
        }

        private void LoadLastUsername()
        {
            txtName.Text = Config.GetLastLoggedInUsername();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            // verify the user input
            bool hasEmptyTextBox = Controls.OfType<TextBox>()
                               .Any(tb => String.IsNullOrWhiteSpace(tb.Text));

            if (hasEmptyTextBox)
            {
                MessageBox.Show("Bạn cần điển đầy đủ Tên và Mật khẩu");
                return;
            }

            User loginUser = new User();
            loginUser.Name = txtName.Text.Trim();
            loginUser.Password = txtPass.Text.Trim();

            loginUser = loginUser.Login();

            if (loginUser.UserId > 0) // login succeed
            {
                // Save last login
                Config.SaveLoggedInUsername(loginUser.Name);
                this.Hide();

                // set the admin mode on.
                frmAdmin adminForm = new frmAdmin();
                adminForm.StartPosition = FormStartPosition.CenterScreen;
                adminForm.ShowDialog(this);

                this.Close();
            }
            else
                MessageBox.Show("Tên và mật khẩu không đúng.");
        }

        private void frmLoginForm_Enter(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtName.Text))
            {
                txtPass.TabIndex = 0;
            }
        }
    }
}
